export default {
	namespaced:true,
	state:()=>{
		return {
			// count:0
			cart:JSON.parse(uni.getStorageSync('cart') || '[]')
		}
	},
	mutations:{
		updateAllGoodsState(state,newState){
			state.cart.forEach(item=>item.goods_state = newState);
			this.commit('cart_m/saveToStorage')
		},
		removeGoodsById(state,goods_id){
			state.cart = state.cart.filter(item=>item.goods_id !== goods_id);
			this.commit('cart_m/saveToStorage')
		},
		updateGoodsCount(state,goods){
			// const findResult  = state.cart.find(item=>item.goods_id == goods.goods_id);
			// if(findResult){
			// 	findResult.goods_count = goods.goods_count;
			// 	this.commit('cart_m/saveToStorage');
			// }
			const findResult = state.cart.find(item=>item.goods_id == goods.goods_id);
			if(findResult){
				findResult.goods_count = goods.goods_count;
				//console.log(www);
				// this.commit('cart_m/saveToStorage')
				this.commit('cart_m/saveToStorage')
			}
		},
		updateGoodsState(state,goods){
			const findResult  = state.cart.find(item=>item.goods_id == goods.goods_id);
			if(findResult){
				findResult.goods_state = goods.goods_state;
				this.commit('cart_m/saveToStorage');
			}
		},
		addToCart(state,goods){
			const findResult  = state.cart.find(item=>item.goods_id === goods.goods_id);
			if(findResult){
				findResult.goods_count++;
			}else{
				state.cart.push(goods);
			};
			this.commit('cart_m/saveToStorage');
		},
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart));
		}
	},
	actions:{},
	getters:{
		checkedGoodsAmount(state){
			return state.cart.filter(item=>item.goods_state).reduce((total,item)=>{return total += item.goods_price * item.goods_count},0).toFixed(2)
		},
		checkedCount(state){
			// return state.cart.filter(item=>item.goods_state).reduce((total,item)=>total += item.goods_count,0);
			const resultFilter = state.cart.filter(item=>item.goods_state == true);
						 // 符合条件的goods_count 进行累加
			const sum = resultFilter.reduce((sum,item)=>sum += item.goods_count,0)
			return sum;
		},
		total(state){
			let sum = 0;
			state.cart.forEach(goods=>sum += goods.goods_count);			
			return sum;
		}
	},
}